package com.redstar.HappyRefresh.controller;

import com.redstar.HappyRefresh.cache.UserInfo;
import com.redstar.HappyRefresh.config.QiNiuConfig;
import com.redstar.HappyRefresh.pojo.File;
import com.redstar.HappyRefresh.pojo.Result;
import com.redstar.HappyRefresh.pojo.Setting;
import com.redstar.HappyRefresh.service.FileService;
import com.redstar.HappyRefresh.service.SettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@Slf4j
@RequestMapping("/luckyjourney/file")
public class FileController {

    @Autowired
    private FileService fileService;
    @Autowired
    private QiNiuConfig qiNiuConfig;
    @Autowired
    private SettingService settingService;

    @PostMapping
    public Result saveFile(String fileKey) { // 保存文件
        if (ObjectUtils.isEmpty(fileKey)) {
            log.error("save方法：fileKey为null，这让我怎么保存");
            return Result.fail().message("fileKey为null，这让我怎么保存");
        }
        Long userId = UserInfo.get();
        return Result.succeed().data(fileService.saveFile(fileKey, userId));
    }

    @GetMapping("/getToken")
    public Result token() { // 获取文件上传的token
        return Result.succeed().data(qiNiuConfig.uploadToken());
    }

    @GetMapping("/{fileId}")
    public void getUUid(HttpServletResponse response, @PathVariable Long fileId) throws IOException {
        if (ObjectUtils.isEmpty(fileId)) {
            log.error("getUUid方法：fileId为null，这让我怎么操作");
        }
        File file = fileService.getFileTrustUrl(fileId); // 获取文件真实的url
        if (!ObjectUtils.isEmpty(file)) {
            response.setContentType(file.getType());
            response.sendRedirect(file.getFileKey());
        }
    }
}
